<!--
  - Copyright (c) 2019.  武汉中科图灵科技有限公司
  - Date :  2019/1/5
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.6.2
  -->

<template>
    <div class="app-container calendar-list-container no-padding" v-if="Show">
        <el-container>
            <div class="flex-left-pannel flex-left-pannel__noright">
                <el-row>
                    <div class="xf-tabletop-handles">
                        <div class="xf-tabhd-left">
                            <el-button class="filter-item" @click="handleCreate" type="primary" size="mini">添加网关设备</el-button>
                        </div>
                        <div class="xf-tabhd-right">
                            设备编号
                            <el-input v-model="listQuery.no" placeholder="请输入设备编号" class="xf-query-input" size="mini"></el-input>
                            <el-button @click="tableQuery" type="primary" size="mini">查询</el-button>
                            <el-popover placement="bottom-end" width="700" class="xf-custom-poper" @show="getSelected" v-model="visible2">
                                <div class="xf-double-form">
                                    <div class="xf-dbform-item">
                                        <div class="xf-dbform-item__sleft">
                                            <p class="xf-dbform-item__label">状态</p>
                                            <el-select placeholder="请选择状态" v-model="slistQuery.status">
                                                <el-option label="全部" value="-1"></el-option>
                                                <el-option label="正常" value="1"></el-option>
                                                <el-option label="故障" value="0"></el-option>
                                            </el-select>
                                        </div>
                                        <div class="xf-dbform-item__sright">
                                            <p class="xf-dbform-item__label">厂商</p>
                                            <el-select placeholder="请选择厂商" v-model="slistQuery.manufacturer">
                                                <el-option :label="item" :value="item" v-for="item in manufeList" :key="item"></el-option>
                                            </el-select>
                                        </div>
                                    </div>
                                    <div class="xf-dbform-item">
                                        <div class="xf-dbform-item__sleft">
                                            <p class="xf-dbform-item__label">系列</p>
                                            <el-select placeholder="请选择系列" v-model="slistQuery.equipmentType">
                                                <el-option :label="item" :value="item" v-for="item in equipmentTypeList" :key="item"></el-option>
                                            </el-select>
                                        </div>
                                    </div>
                                    <div class="xf-dbform-item">
                                        <div class="xf-dbform-item__sleft">
                                            <p class="xf-dbform-item__label">型号</p>
                                            <el-input v-model="slistQuery.model" placeholder="请输入型号"></el-input>
                                        </div>
                                        <div class="xf-dbform-item__sright">
                                            <p class="xf-dbform-item__label">位置描述</p>
                                            <el-input v-model="slistQuery.positionDescription" placeholder="请输入位置描述"></el-input>
                                        </div>
                                    </div>
                                </div>
                                <div style="text-align: left; margin: 0; margin-top:20px;">
                                    <el-button size="mini" type="primary" @click="pointerQuery">查询</el-button>
                                    <el-button size="mini" @click="visible2 = false" type="text">取消</el-button>
                                </div>
                                <el-button slot="reference" type="text" size="mini">高级查询</el-button>
                            </el-popover>
                        </div>
                    </div>
                </el-row>
                <el-table key='tableKey' :data="list" v-loading.body="listLoading" fit style="width: 100%">
                    <el-table-column label="序号" width="50">
                        <template slot-scope="scope">
                            <span>{{scope.row.id}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            <span>{{scope.row.status}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="编号">
                        <template slot-scope="scope">
                            <span>{{scope.row.no}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="厂商">
                        <template slot-scope="scope">
                            <span>{{scope.row.manufacturer}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="系列">
                        <template slot-scope="scope">
                            <span>{{scope.row.equipmentType}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="型号">
                        <template slot-scope="scope">
                            <span>{{scope.row.model}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="位置">
                        <template slot-scope="scope">
                            <span>{{scope.row.positionDescription}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="130" fixed="right">
                        <template slot-scope="scope">
                          <span @click="handleUpdate(scope.row)" class="comm-table-btn"><icon-svg icon-class="bianji" style="fill:#50E3C2" /></span>
                          <span @click="handleDelete(scope.row)" class="comm-table-btn"><icon-svg icon-class="shanchu" style="fill:#50E3C2" /></span>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-show="!listLoading" class="pagination-container">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,15,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
                </div>
            </div>
        </el-container>
        <slider-panel :Show.sync="dialogFormVisible" custom-class="out-side-frame">
          <div class="form-content-frame">
            <el-form :model="form" ref="form" :rules="rules" label-width="100px" label-position='top' @submit.native.prevent>
              <el-form-item label="设备编号" prop="no">
                  <el-input v-model.trim="form.no" placeholder="请输入设备编号"></el-input>
              </el-form-item>
              <el-form-item label="厂商 / 系列 / 型号" prop="entity">
                  <el-cascader :options="entityOptions" filterable :clearable='true' v-model="form.entity" style="width:100%">
                  </el-cascader>
              </el-form-item>
              <el-form-item label="位置信息" prop="isgeographicalPositionSign">
                  <el-input v-model="form.isgeographicalPositionSign" placeholder="请标记地点" class="xf-input-withbtn" :disabled="true">
                      <el-button plain slot="append" class="xf-input-withbtn__rightbtn" @click="handleSelectMap">
                          <icon-svg icon-class="checklocal" />标记地点</el-button>
                  </el-input>
              </el-form-item>
              <el-form-item label="位置描述" prop="positionDescription">
                  <el-input v-model.trim="form.positionDescription"></el-input>
              </el-form-item>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')" size="mini" native-type="submit">确 定</el-button>
                <el-button v-else type="primary" @click="update('form')" size="mini" native-type="submit">确 定</el-button>
                <el-button @click="cancel('form')" type="text" size="mini">取 消</el-button>
            </el-form>
          </div>
        </slider-panel>
        <el-dialog :visible.sync="dialogFormChildVisible" :show-close='false' top="7vh" custom-class="fulldialog-child" :close-on-click-modal='false' :close-on-press-escape='false'>
            <div class="dialog-custom__header">
                <div class="dialog-custom__header-title">标记网关设备
                    <span v-if="form.no.length>0">-“{{equipmentType}} {{form.no}}”</span>
                </div>
                <div class="dialog-custom__btns">
                    <el-button type="primary" size="mini" @click="savelnglat">保存</el-button>
                    <el-button type="text" size="mini" @click="mapCancel">取消</el-button>
                </div>
            </div>
            <div class="dialog-map__container">
                <div class="dailogmap-top-search">
                    <el-autocomplete
                      v-model="searchText"
                      :fetch-suggestions="onSearchResult"
                      :trigger-on-focus="false"
                      placeholder="请搜索或选择地点"
                      @select="handleSelect"
                      popper-class="dailog-addressbox-list"
                      suffix-icon="el-icon-search"
                    >
                      <template slot-scope="{ item }">
                        <span class="name">{{ item.name }}</span>
                        <span class="addr">{{ item.district }}</span>
                      </template>
                    </el-autocomplete>
                </div>
                <el-amap vid="amap" ref="map" :rotateEnable='true' :plugin="plugin" :center="center" :zoom="zoom" :events="events" class="mapset" :resizeEnable="resized">
                    <el-amap-marker :position="center" :events="markerEvents">
                    </el-amap-marker>
                    <el-amap-info-window :position="center" :content="lnglatstr" :visible="infowvisible" :events="infowevents"></el-amap-info-window>
                </el-amap>
            </div>
        </el-dialog>
        <el-dialog title="删除网关设备" :visible.sync="dialogDeleteVisible" :show-close='false' custom-class="xf-jc-dialog" width="360px">
            <div class="xf-jc-deletect">
                <p>确定删除此网关设备？</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" size="mini" @click="deleteD(currentSelectObj)">删除</el-button>
                <el-button size="mini" @click="dialogDeleteVisible = false" type="text">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import {
  page,
  selectQuery,
  createSelected,
  getObj,
  addColObj,
  delObj,
  putObj
} from "@/api/device/deviceCollectingDevice/index";
import sliderPanel from '@/components/SliderPanel'

export default {
  name: "deviceTab",
  props:["Show"],
  components: {sliderPanel},
  data() {
    let self = this;
    return {
      center: [114.305215, 30.59293],
      lnglatstr: "暂无数据",
      searchOption: {
        city: "武汉",
        citylimit: false
      },
      searchText:'',
      equipmentType:'',
      searchResult: [],
      lng: 0,
      lat: 0,
      zoom: 15,
      resized: true,
      infowvisible: true,
      markerEvents: {
        click: e => {
          self.infowvisible = true;
        }
      },
      infowevents: {
        close() {
          self.infowvisible = false;
        }
      },
      events: {
        init: o => {
          o.setMapStyle('amap://styles/117f36d1e643cfd46d21660d866df29e');
          AMapUI.loadUI(["control/BasicControl"], function(BasicControl) {
            //缩放控件
            o.addControl(
              new BasicControl.Zoom({
                position: "rb" //右下角缩放
              })
            );
          });
        },
        click: e => {
          //点击地图事件
          // 这里通过高德 SDK 完成。
	                let geocoder = new AMap.Geocoder({
	                  radius: 1000,
	                  extensions: "all"
                  });
                  self.center = [e.lnglat.lng, e.lnglat.lat];
	                geocoder.getAddress(self.center, function(status, result) {
	                  if (status === 'complete' && result.info === 'OK') {
	                    if (result && result.regeocode) {
	                      self.lnglatstr =result.regeocode.formattedAddress;

	                    }
	                  }
	                });
          this.infowvisible = true;
        }
      },
      plugin: [
        {
          pName: "Geolocation",
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lnglatstr = result.formattedAddress
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.center = [self.lng, self.lat];
                  self.$nextTick();
                }
              });
            }
          }
        },
        {
          pName: "Scale",
          events: {}
        }
      ],
      visible2: false,
      showdownload: false,
      form: {
        no: "",
        entity: [],
        isgeographicalPositionSign: "",
        positionDescription: ""
      },
      rules: {
        no: [
          {
            required: true,
            message: "请输入设备编号",
            trigger: "blur"
          },
          {
            min: 1,
            max: 100,
            message: "最多允许输入100个字符",
            trigger: "blur"
          }
        ],
        entity: [
          {
            required: true,
            message: "请选择 厂商 / 系列 / 型号",
            trigger: ["blur"]
          }
        ],
        isgeographicalPositionSign: [
          {
            required: true,
            message: "请选择位置",
            trigger: "change"
          }
        ],
        positionDescription: [
          {
            required: true,
            message: "请输入位置描述",
            trigger: "blur"
          },
          {
            min: 1,
            max: 50,
            message: "最多允许输入50个字符",
            trigger: "blur"
          }
        ]
      },
      list: null,
      total: null,
      listLoading: true,
      slistQuery: {
        status: "-1",
        manufacturer: "全部",
        equipmentType: "全部",
        model: "",
        positionDescription: ""
      },
      listQuery: {
        page: 1,
        limit: 15,
        no: undefined
      },
      dialogFormVisible: false,
      dialogFormChildVisible: false,
      dialogDeleteVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑网关设备",
        create: "添加网关设备"
      },
      tableKey: 0,
      manufeList: [],
      equipmentTypeList: [],
      entityOptions: [],
      editlnglat: "", //服务器保存的经纬度
      currentSelectObj: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    mapCancel() {
      this.dialogFormChildVisible = false;
    },
    savelnglat() {
      this.dialogFormChildVisible = false;
      this.form.isgeographicalPositionSign = '已标记';
      this.editlnglat = this.center.join(",") || "";
    },
    handleSelect(item){

        let lnglat = item.location;

        this.searchText = item.name;

        let self = this;
        if(lnglat){
          this.center = [lnglat.lng, lnglat.lat];
        }else{
             let geocoder = new AMap.Geocoder({
	                  radius: 1000,
                    extensions: "all",
                  });
	                geocoder.getLocation(item.name, function(status, result) {

	                  if (status === 'complete' && result.info === 'OK') {
	                    if (result && result.geocodes) {
                        self.center = [result.geocodes[0].location.lng,result.geocodes[0].location.lat];
                        self.zoom = 12.2
	                    }
	                  }
                  });

        }

        this.lnglatstr = this.searchText;
        this.infowvisible = true;
    },
    onSearchResult(pois,cb) {
       let self = this;
       let searchkey = this.searchText;
       AMap.plugin(['AMap.Autocomplete'], function() {
         var autoOptions = {
            city: '', // 城市，默认全国
          }
         var autoComplete = new AMap.Autocomplete(autoOptions)
         autoComplete.search(searchkey, function(status, result) {
            // 搜索成功时，result即是对应的匹配数据
            if(result){
              let results = result.tips;
              if(results){
                cb(results);
              } else {
                //搜索无结果
                cb("")
              }
            }
          })
       })
    },
    handleSelectMap() {
      this.dialogFormChildVisible = true;

      if (this.editlnglat.length > 0) {

        let stringArr = JSON.parse(JSON.stringify(this.editlnglat)).split(",");
        let lng = Number(stringArr[0]);
        let lat = Number(stringArr[1]);
        this.center = [lng, lat];

        let self = this;
         let geocoder = new AMap.Geocoder({
	                  radius: 1000,
	                  extensions: "all"
                  });
	                geocoder.getAddress(self.center, function(status, result) {
	                  if (status === 'complete' && result.info === 'OK') {
	                    if (result && result.regeocode) {
	                      self.lnglatstr =result.regeocode.formattedAddress;

	                    }
	                  }
	                });

      }
    },
    handleClick() {},
    deleteD(row) {
      this.dialogDeleteVisible = false;
      delObj(row.id).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        this.getList();
      });
    },
    handleDelete(row) {
      this.dialogDeleteVisible = true;
      this.currentSelectObj = row;
    },
    tableQuery() {
      this.getList();
    },
    getSelected() {
      // 获取高级查询条件
      selectQuery().then(response => {
        this.manufeList = response.data.manufacturer;
        this.equipmentTypeList = response.data.equipmentType;
      });
    },
    pointerQuery() {
      // 高级查询
      this.visible2 = false;
      this.listLoading = true;
      // 取消绑定并合并查询条件
      let contactKeys = Object.assign(
        JSON.parse(JSON.stringify(this.listQuery)),
        JSON.parse(JSON.stringify(this.slistQuery))
      );
      page(contactKeys).then(response => {
        this.list = response.data.rows;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleCreate() {
      this.dialogStatus = "create";
      this.handlerest();
      this.dialogFormVisible = true;

      createSelected().then(response => {
        this.entityOptions = response.data.options;
      });
    },
    handlerest() {
      this.form.no = "";
      this.form.entity = [];
      this.form.isgeographicalPositionSign = "";
      this.form.positionDescription = "";
      this.editlnglat = "";
      this.searchText = "";
    },
    handleUpdate(row) {
      createSelected({ id: row.id })
        .then(response => {
          this.form.entity = response.data.selectedOptions;
          this.form.no = response.data.deviceSensor.no;
          this.form.isgeographicalPositionSign = '已标记';
          this.editlnglat = response.data.deviceSensor.geographicalPositionSign;

          this.form.positionDescription =
            response.data.deviceSensor.positionDescription;

          this.form.id = row.id;
          this.entityOptions = response.data.options;

          this.dialogFormVisible = true;
          this.dialogStatus = "update";
          this.equipmentType=row.equipmentType;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          addColObj({
            no: this.form.no,
            entity: JSON.stringify(this.form.entity),
            geographicalPositionSign: this.editlnglat,
            positionDescription: this.form.positionDescription
          }).then(() => {
            this.dialogFormVisible = false;
            this.handlerest();
            this.$refs[formName].resetFields();

            this.getList();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          putObj({
            id: this.form.id,
            no: this.form.no,
            entity: JSON.stringify(this.form.entity),
            geographicalPositionSign: this.editlnglat,
            positionDescription: this.form.positionDescription
          })
            .then(() => {
              this.dialogFormVisible = false;

              this.$refs[formName].resetFields();
              this.handlerest();
              this.getList();
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
                duration: 2000
              });
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;

      this.handlerest();
      this.$refs[formName].resetFields();
    },
    download() {},
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      page(this.listQuery).then(response => {
        this.list = response.data.rows;
        this.total = response.data.total;
        this.listLoading = false;
      });
    }
  },
  mounted() {

  },
  watch:{
    Show:function(val){
      if (val) {
        this.getList();
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.flex-left-pannel__noright {
  padding-right: 0;
}
.xf-input-withbtn__rightbtn {
  border: 0;
  height: 34px;
  margin-top: -8px !important;
}
.device-add-dialog {
  .el-dialog__title {
    font-size: 32px;
  }
  .el-dialog__header {
    margin-top: 20px;
  }
  .custom-dialog-btn {
    position: absolute;
    font-size: 30px;
    left: 40px;
    top: 20px;
    color: #fff;
    &:hover {
      cursor: pointer;
    }
  }
  .dialog-footer {
    text-align: left;
  }
}
// 精准查询
.xf-double-form{
  .xf-dbform-item{
    display: flex;
    justify-content: space-between;
    .xf-dbform-item__sleft{
      .el-input{
        width: 320px;
      }
    }
    .xf-dbform-item__sright{
      .el-input{
        width: 320px;
      }
    }
  }
}
.fulldialog-child {
  width: 1100px;
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding: 0;
  }
  .dialog-custom__header {
    display: flex;
    padding: 15px 20px;
    justify-content: space-between;
    .dialog-custom__header-title {
      font-size: 32px;
      line-height: 36px;
      color: #50E3C2;
    }
  }
  .dialog-map__container {
    width: 1100px;
    height: 750px;
    position: relative;
    overflow: hidden;
  }
  .amap-logo {
    display: none !important;
  }
  .amap-copyright {
    display: none !important;
  }
  .amap-ui-control-zoom {
    width: 35px;
    a {
      width: 35px;
    }
  }
  .amap-controls {
    .amap-geolocation-con {
      right: 0;
      right: 30px;
      left: auto !important;
      bottom: 106px !important;
      .amap-geo {
        right: 0;
        cursor: pointer;
      }
    }
  }
  .dailogmap-top-search{
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9;
    width: 320px;
    .el-autocomplete{
      width: 100%;
    }
  }
  .amap-info {
    transform: translateY(-30px);
  }
}
// 搜索结果列表
.dailog-addressbox-list{
      li{
        .addr{
          font-size: 12px;
          color: #999;
        }
      }
}
.device-add-dialog > div {
  width: 500px;
  margin: 0 auto;
}
</style>
